package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.vo.DefScoreRuleDTO;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.DefScoreRuleMapper;
import com.ruoyi.system.domain.DefScoreRule;
import com.ruoyi.system.service.IDefScoreRuleService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 得分规则Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-10-11
 */
@Service
public class DefScoreRuleServiceImpl implements IDefScoreRuleService 
{
    private static final Logger log = LoggerFactory.getLogger(DefScoreRuleServiceImpl.class);
    @Autowired
    private DefScoreRuleMapper defScoreRuleMapper;

    /**
     * 查询得分规则
     * 
     * @param id 得分规则主键
     * @return 得分规则
     */
    @Override
    public DefScoreRule selectDefScoreRuleById(Long id)
    {
        return defScoreRuleMapper.selectDefScoreRuleById(id);
    }

    /**
     * 查询得分规则列表
     * 
     * @param defScoreRule 得分规则
     * @return 得分规则
     */
    @Override
    public List<DefScoreRule> selectDefScoreRuleList(DefScoreRule defScoreRule)
    {
        return defScoreRuleMapper.selectDefScoreRuleList(defScoreRule);
    }

    @Override
    public List<DefScoreRule> ruleList(DefScoreRule defScoreRule) {
        List<DefScoreRule> rules = defScoreRuleMapper.selectDefScoreRuleList(defScoreRule);
        Map<Long, List<DefScoreRule>> ruleMap = rules.stream().collect(Collectors.groupingBy(DefScoreRule::getPid));
        List<DefScoreRule> ruleList = ruleMap.getOrDefault(0L, new ArrayList<>());
        for (DefScoreRule rule : ruleList) {
            rule.setChildren(ruleMap.get(rule.getId()));
        }
        return ruleList;
    }

    /**
     * 新增得分规则
     * 
     * @param defScoreRule 得分规则
     * @return 结果
     */
    @Override
    public int insertDefScoreRule(DefScoreRule defScoreRule)
    {
        defScoreRule.setCreateTime(DateUtils.getNowDate());
        return defScoreRuleMapper.insertDefScoreRule(defScoreRule);
    }

    /**
     * 修改得分规则
     * 
     * @param defScoreRule 得分规则
     * @return 结果
     */
    @Override
    public int updateDefScoreRule(DefScoreRule defScoreRule)
    {
        return defScoreRuleMapper.updateDefScoreRule(defScoreRule);
    }

    /**
     * 批量删除得分规则
     * 
     * @param ids 需要删除的得分规则主键
     * @return 结果
     */
    @Override
    public int deleteDefScoreRuleByIds(Long[] ids)
    {
        return defScoreRuleMapper.deleteDefScoreRuleByIds(ids);
    }

    /**
     * 删除得分规则信息
     * 
     * @param id 得分规则主键
     * @return 结果
     */
    @Override
    public int deleteDefScoreRuleById(Long id)
    {
        return defScoreRuleMapper.deleteDefScoreRuleById(id);
    }

    @Override
    public Boolean importDefScoreRule(MultipartFile file, Integer scoreType) {
        log.info("开始导入规则");
        int success = 0;
       try {
           Workbook workbook = new XSSFWorkbook(file.getInputStream());
           Sheet workSheet = workbook.getSheetAt(0);  // Assuming the first worksheet
           int nameColumn = -1, typeColumn = -1, scoreColumn = -1, remarkColumn = -1;
           Row headerRow = workSheet.getRow(0);

           for (int column = 0; column < headerRow.getLastCellNum(); column++) {
               String val = headerRow.getCell(column).getStringCellValue().trim().toLowerCase();
               switch (val) {
                   case "规则名称":
                       nameColumn = column;
                       break;
                   case "类型":
                       typeColumn = column;
                       break;
                   case "赋值规则":
                       scoreColumn = column;
                       break;
                   case "备注":
                       remarkColumn = column;
                       break;
               }
           }
           if (nameColumn == -1 || typeColumn == -1 || scoreColumn == -1 || remarkColumn == -1) {
               throw new RuntimeException("无效的表格格式");
           }
           List<DefScoreRuleDTO> list = new ArrayList<>();
           for (int rowIndex = 1; rowIndex <= workSheet.getLastRowNum(); rowIndex++) {
               Row row = workSheet.getRow(rowIndex);
               String name = getCellValueAsString(row.getCell(nameColumn)).trim();
               String type = getCellValueAsString(row.getCell(typeColumn)).trim();
               String role = getCellValueAsString(row.getCell(scoreColumn)).trim();
               String remark = getCellValueAsString(row.getCell(remarkColumn)).trim();
               if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(type) && StringUtils.isNotEmpty(role) && StringUtils.isNotEmpty(remark)) {
                   DefScoreRuleDTO rule = new DefScoreRuleDTO();
                   rule.setParentName(name);
                   rule.setRuleName(type);
                   rule.setRuleType(scoreType);
                   rule.setScoreRule(role);
                   rule.setRemark(remark);
                   rule.setCreateTime(DateUtils.getNowDate());
                   rule.setPid(0L);
                   list.add(rule);
               }
           }
           LoginUser loginUser = SecurityUtils.getLoginUser();
           DefScoreRule query = new DefScoreRule();
           query.setDrillId(Long.valueOf(loginUser.getDrillId()));
           query.setRuleType(scoreType);
           List<DefScoreRule> all = defScoreRuleMapper.selectDefScoreRuleList(query);
           DefScoreRule parent = null;
           for (DefScoreRuleDTO rule : list) {
               parent = all.stream().filter(r -> r.getRuleName().equals(rule.getParentName()) && r.getPid() == 0).findFirst().orElse(null);
               if (parent == null) {
                   parent = new DefScoreRule();
                   parent.setRuleName(rule.getParentName());
                   parent.setRuleType(scoreType);
                   parent.setDrillId(Long.valueOf(loginUser.getDrillId()));
                   defScoreRuleMapper.insertDefScoreRule(parent);
                   all.add(parent);
               }
               rule.setPid(parent.getId());
               DefScoreRule child = all.stream().filter(r -> r.getRuleName().equals(rule.getRuleName())).findFirst().orElse(null);
               if (child == null) {
                   child = new DefScoreRule();
                   BeanUtils.copyProperties(rule, child);
                   child.setCreateTime(DateUtils.getNowDate());
                   child.setDrillId(Long.valueOf(loginUser.getDrillId()));
                   success += defScoreRuleMapper.insertDefScoreRule(child);
               }
           }
       } catch (Exception e) {
            log.error("导入得分规则异常", e);
       }
       log.info("导入得分规则成功：{} 行" , success);
    	return success > 0;
    }

    private static String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return "";
        }

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula(); // 或者根据需要计算公式值
            default:
                return "";
        }
    }

}
